<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="订单编号">
              <a-input v-model="queryParam.numbering" placeholder="请输入订单编号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="商品编号">
              <a-input v-model="queryParam.commodity_numbering" placeholder="请输入商品编号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="活动编号">
              <a-input v-model="queryParam.commodity_activity_id" placeholder="请输入活动编号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="订单状态">
              <a-select v-model="queryParam.status" placeholder="请选择">
                <a-select-option value="0">全部</a-select-option>
                <a-select-option value="1">待发货</a-select-option>
                <a-select-option value="2">已发货</a-select-option>
                <a-select-option value="3">已取消</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="收货人姓名">
              <a-input v-model="queryParam.client_search_name" placeholder="请输入收货人姓名"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="收货人手机号">
              <a-input v-model="queryParam.client_search_phone" placeholder="请输入收货人手机号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="代理商">
              <a-input v-model="queryParam.agent_search" placeholder="请输入代理商名称或手机号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="创建时间">
              <a-range-picker :allowClear="true" :defaultValue="createdAtRange" ref="createdAtRangePicker" @change="createdAtRangePickerOnChange"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              <a-button style="margin-left: 8px" @click="handleExport">导出</a-button>
              <a-button style="margin-left: 8px" @click="handleExport(true)">大数据导出</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <s-table
      ref="table"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :pageNum="parseInt(queryParam.page || 1)"
      :pageSize="parseInt(queryParam.per_page || 20)"
      showPagination="auto"
    >
      <span slot="title">
        <a-row type="flex" justify="start" :gutter="16">
          <a-col>
            <a-button @click="exportShipBatchTemplate" type="link">批量发货模板</a-button>
          </a-col>
          <a-col>
            <progress-time-line
              title="批量导入发货信息"
              btn-title="批量导入发货信息"
              :steps="[{ title: '读取文件'}, { title: '上传处理'}, { title: '完成' }]"
              :handle-before="getCourierCompany"
              :handle-raw="handleShipBatch"
              :sending-interval="50"
            />
          </a-col>
          <a-col>
            <a-button @click="exportCancelBatchTemplate" type="link">批量取消模板</a-button>
          </a-col>
          <a-col>
            <progress-time-line
              title="批量导入订单取消"
              btn-title="批量导入订单取消"
              :steps="[{ title: '读取文件'}, { title: '上传处理'}, { title: '完成' }]"
              :handle-raw="handleCancelBatch"
            />
          </a-col>
        </a-row>
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a-row type="flex" justify="start" :gutter="[8, 8]">
            <a-col>
              <a @click="$router.push({ name: 'order_info', params: {id: record.id} })">详情</a>
            </a-col>
            <a-col>
              <a-popover
                title="请输入备注"
                destroyTooltipOnHide
                trigger="click"
                @visibleChange="visible => !visible && (remark = '')"
              >
                <template slot="content">
                  <a-row :gutter="[15, 15]">
                    <a-col>
                      <a-textarea v-model="remark" :row="4" ref="remarkPopover" placeholder="请输入备注"/>
                    </a-col>

                    <a-col style="display: flex; justify-content: center;">
                      <a-button type="primary" @click="() => handleRemark(record)">确认</a-button>
                    </a-col>
                  </a-row>
                </template>
                <a>备注</a>
              </a-popover>
            </a-col>
          </a-row>

          <a-row type="flex" justify="start" :gutter="[8, 8]">
            <a-col>
              <a @click="orderDelivery(record)" v-if="[1, 2].includes(record.status)">发货</a>
            </a-col>
            <a-col>
              <!--待发货可以取消 (record.status === 1)-->
              <a-popconfirm placement="top" @confirm="cancelOrder(record)" v-if="record.status === 1">
                <template slot="title">
                  确定要取消吗?
                </template>
                <a>取消</a>
              </a-popconfirm>
            </a-col>
          </a-row>
        </template>
      </span>
    </s-table>

    <a-modal
      title="订单发货"
      v-if="state.showOrderDelivery"
      :visible="state.showOrderDelivery"
      :confirm-loading="state.orderDeliveryConfirmLoading"
      @cancel="state.showOrderDelivery = false"
      @ok="() => $refs['orderDelivery'].handleSubmit().then(_ => {
        state.showOrderDelivery = false
        $refs['table'].refresh()
      })"
    >
      <order-delivery
        ref="orderDelivery"
        :id="parseInt(this.currentOrderId)"
        :show-button="false"
        :direct-edit="true"
      />
    </a-modal>
  </a-card>
</template>

<script>
import { Ellipsis, STable } from '@/components'
import { cancelOrderByNumbering, getOrderList, patchOrderExpressDelivery, patchOrderRemark } from '@/api/order'
import { formatAmount } from '@/utils/util'
import OrderDelivery from '@/components/OrderDelivery/OrderDelivery'
import ProgressTimeLine from '@/components/ProgressTimeLine/ProgressTimeLine'
import XLSX from 'xlsx'
import { getCourierCompanyList } from '@/api/system'
import cloneDeep from 'lodash.clonedeep'
import moment from 'moment'

const statusMap = {
    1: {
      text: '待发货'
    },
    2: {
      text: '已发货'
    },
    3: {
      text: '已取消'
    }
  }

  export default {
    name: 'List',
    components: {
      ProgressTimeLine,
      OrderDelivery,
      STable,
      Ellipsis
    },
    created () {
      this.queryParam = Object.assign(this.queryParam, cloneDeep(this.$route.query))
      if (this.queryParam.created_at_begin && this.queryParam.created_at_end) {
        this.createdAtRange = [moment(this.queryParam.created_at_begin), moment(this.queryParam.created_at_end)]
      }
    },
    data () {
      return {
        // 查询参数
        queryParam: {
          created_at_begin: moment().subtract(1, 'months').format('YYYY-MM-DD'), // 默认最近一个月
          created_at_end: moment().format('YYYY-MM-DD')
        },
        createdAtRange: [moment().subtract(1, 'months'), moment()],
        // 表头
        columns: [
          {
            title: '订单编号',
            dataIndex: 'numbering'
          },
          {
            title: '商品名称',
            dataIndex: 'commodity_snapshot.name'
          },
          {
            title: '活动编号',
            dataIndex: 'commodity_activity_snapshot.numbering'
          },
          {
            title: '代理',
            dataIndex: 'agent.name'
          },
          {
            title: '代理手机号',
            dataIndex: 'agent.phone'
          },
          {
            title: '收件人',
            dataIndex: 'client_name'
          },
          {
            title: '收件人手机号',
            dataIndex: 'client_phone'
          },
          {
            title: '订单总额',
            dataIndex: 'total_amount',
            customRender: amount => {
              return formatAmount(amount)
            }
          },
          {
            title: '状态',
            dataIndex: 'status',
            customRender: status => {
              return statusMap[status].text
            }
          },
          {
            title: '备注',
            dataIndex: 'management_notes'
          },
          {
            title: '创建时间',
            dataIndex: 'created_at'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        firstLoadData: true,
        loadData: parameter => {
          let query = null
          if (this.firstLoadData) { // 第一次加载数据,需要以 router query 为准
            this.firstLoadData = false
            query = cloneDeep(Object.assign(parameter, this.queryParam))
          } else {
            query = cloneDeep(Object.assign(this.queryParam, parameter))
          }
          try {
            // 把搜索条件放入 query
            this.$router.push({ path: this.$route.fullPath, query })
          } catch (e) {
          }

          return getOrderList(query)
        },
        currentOrderId: null,
        state: {
          showOrderDelivery: false,
          orderDeliveryConfirmLoading: false,
          remarkVisible: {}
        },
        remark: '',
        companyNameWithId: null
      }
    },
    methods: {
      createdAtRangePickerOnChange (date, dateString) {
        this.queryParam.created_at_begin = dateString[0]
        this.queryParam.created_at_end = dateString[1]
      },
      handleReset () {
        this.queryParam = {}
        this.$router.push({ query: {} })
        this.$refs.createdAtRangePicker.$refs.picker.clearSelection(new MouseEvent('click'))
        this.$refs.table.refresh(true)
      },
      handleExport (isAsync = false) {
        const exportParam = { export: true }
        ;(isAsync === true) && Object.assign(exportParam, { async: true })

        getOrderList(Object.assign(exportParam, this.queryParam)).then(_ => {
          (isAsync === true) && this.$notification.success({ message: '添加任务成功,请关注[系统-异步导出任务]' })
        })
      },
      cancelOrder (record) {
        cancelOrderByNumbering(record.numbering).then(res => {
          this.$refs['table'].refresh()
        })
      },
      orderDelivery (record) {
        this.currentOrderId = record.id.toString()
        this.state.showOrderDelivery = true
      },
      handleRemark (record) {
        patchOrderRemark({
          'id': record.id,
          'remark': this.remark
        }).finally(_ => {
          this.$refs['table'].refresh()
        })
      },
      handleCancelBatch (item, timeline) {
        return new Promise(resolve => {
          cancelOrderByNumbering(item['订单编号'], { silent: true })
            .then(res => {
              timeline.push({ color: 'green', content: ['订单编号: ' + item['订单编号']] })
            })
            .catch(err => {
              timeline.push({
                color: 'red',
                content: [
                  '订单编号: ' + item['订单编号'],
                  err.response.data.message || ''
                ]
              })
            })
            .finally(_ => {
              resolve()
            })
        })
      },
      async getCourierCompany () {
        // 获取快递公司
        if (this.companyNameWithId === null) {
          this.companyNameWithId = {}
          const companyList = await getCourierCompanyList({ per_page: 999 })
          companyList.data.forEach(company => {
            this.companyNameWithId[company.name] = company.id
          })
        }
      },
      handleShipBatch (item, timeline) {
        return new Promise(resolve => {
          try {
            if (item['订单编号'] === undefined) {
              throw new Error('缺失订单编号')
            }

            // 整理提交数据
            const uploadData = {
              numbering: item['订单编号'],
              courier_information: []
            }
            const courierNumbering = item['快递单号'].toString().split('，')
            item['快递公司'].toString().split('，').forEach((courierCompany, index) => {
              if (this.companyNameWithId[courierCompany] === undefined) {
                throw new Error('快递公司不存在: ' + courierCompany)
              }
              if (courierNumbering[index] === undefined) {
                throw new Error(courierCompany + '缺少快递单号')
              }
              uploadData.courier_information.push({
                courier_company_id: this.companyNameWithId[courierCompany],
                tracking_numbering: courierNumbering[index]
              })
            })

            patchOrderExpressDelivery(uploadData, { silent: true }).then(res => {
              timeline.push({
                color: 'green',
                content: [
                  '订单编号: ' + item['订单编号']
                ]
              })
              resolve()
            }).catch(e => {
              timeline.push({
                color: 'red',
                content: [
                  '订单编号: ' + item['订单编号'],
                  e.message || ''
                ]
              })
            })
          } catch (e) {
            timeline.push({
              color: 'red',
              content: [
                '订单编号: ' + item['订单编号'],
                e.message || ''
              ]
            })
          }
        })
      },
      exportCancelBatchTemplate () {
        const ws = XLSX.utils.aoa_to_sheet([
          ['订单编号'],
          ['2008111845344297166']
        ])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'SheetJS')
        XLSX.writeFile(wb, '批量取消模板.xlsx')
      },
      exportShipBatchTemplate () {
        const ws = XLSX.utils.aoa_to_sheet([
          ['订单编号', '快递公司', '快递单号'],
          ['2008111845344297166', '申通,申通,申通', '7704342134321，7704342134321，7704342134321']
        ])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'SheetJS')
        XLSX.writeFile(wb, '批量发货模板.xlsx')
      }
    }
  }
</script>
